/**
 * MIT License
 * 
 * Copyright (c) 2017 CaiDongyu
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.tunnel.client.task;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpTaskManager {

	private static ExecutorService THREAD_POOL = Executors.newCachedThreadPool();
	private static Map<String,HttpTask> TASK_MAP = new HashMap<>();
	
	public static void doTask(int hostIndex, byte[] requestIdBytes, byte[] dataBytes){
		HttpTask task = new HttpTask(hostIndex, requestIdBytes, dataBytes);
		synchronized(TASK_MAP){
//			LogUtil.d("add task："+task.getRequestId());
			TASK_MAP.put(task.getRequestId(),task);
		}
		THREAD_POOL.execute(task);
	}
	
	public static void stopTask(String requestId){
		synchronized(TASK_MAP){
			if(TASK_MAP.containsKey(requestId)){
//				LogUtil.d("ready stop task："+requestId);
				HttpTask tunnelAppTask = TASK_MAP.remove(requestId);
				tunnelAppTask.cancelTask();
			}
		}
	}
	
	public static void stopTask(){
		synchronized(TASK_MAP){
			for(HttpTask task:TASK_MAP.values()){
//				LogUtil.d("ready stop task："+task.getRequestId());
				task.cancelTask();
			}
			TASK_MAP.clear();
		}
	}
}
